<?php

class WorkflowController extends BackOfficeController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>FSM::run('Cms.Workflow.get', array('id'=>$id))->model,
		));
	}
    
    public function accessRules()
    {
        $accessRules = parent::accessRules();
        array_unshift($accessRules, array(
            'deny',
            'actions' => array('admin','index','create','update'),
            'expression' => '!Yii::app()->authManager->isAssigned("administrators", Yii::app()->user->id)',
            'users' => array('*')
        ));
        return $accessRules;
    }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
        $this->actionUpdate();
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	/*public function actionUpdate()
	{
        $workflows = array();
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'workflow-form');
            $result = FSM::run('Cms.Workflow.save', $_POST);
            $model = $result->model; 

            if ($this->post('ajax','') == 'workflow-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }   
            if (! $result->hasErrors()) {
                $this->message = Yii::t('Core','Item has been saved successfully.');
                $this->redirect(array('update', 'id'=>$model->id));
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            if ($id == 0) {
                $model = new Workflow();
                $model->site_id = Yii::app()->cmsManager->site['id'];
                $workflows = FSM::run('Cms.Workflow.getListBySite', array('site_id'=>$model->site_id))->models;
                if (count($workflows))
                    $workflows = CHtml::listData($workflows, 'id', 'name');
            } else {
                $model = FSM::run('Cms.Workflow.get', array('id' => $id))->model;
            }
        }
        
        $sites = FSM::run('Cms.site.getList')->models;
        if (count($sites))
            $sites = CHtml::listData($sites, 'id', 'name');
        $this->render('update', array('model' => $model, 'workflows'=>$workflows, 'sites'=>$sites));
	}*/

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($id = $this->get('id',null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',',$id);
                
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Cms.Workflow.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $this->actionAdmin();
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
        $model=new Workflow('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Workflow']))
            $model->attributes=$_GET['Workflow'];
            
        $model->site_id = Yii::app()->cmsManager->site['id'];

        $this->render('admin',array(
            'model'=>$model,
        ));
	}
    
    public function actionUpdate()
    {
        $id = $this->get('id', 0);
//        $masterLayoutRevision = $this->get('master_layout_revision', 0);
        if ($id)
        {
            $workflow = Workflow::model()->findByPk($id);
        }
        else
        {
            $workflow = new Workflow();
            $workflow->site_id = Yii::app()->cmsManager->site['id'];
        }
        
//        if ($masterLayoutRevision)
//            $workflow->master_layout_revision = $masterLayoutRevision;
        
        //find master layouts of current site
        //$criteria = new CDbCriteria();
//        $criteria->select = 'id, group';
//        $criteria->with = array(
//        'contents'=>array(
//            'select'=>'id, revision_id',
//            'together'=>true,
//        ));
//        $criteria->compare('name', $workflow->site_id);
//        $model = Template::model()->find($criteria);
//        $masterLayouts = array();
//        if (is_object($model) && is_array($model->contents) && count($model->contents))
//        {
//            $masterLayouts = CHtml::listData($model->contents, 'id', 'revision_id');
//        }
//        if (count($masterLayouts))
//            asort($masterLayouts, SORT_NUMERIC);
        //Yii::trace('$model->contents '.CVarDumper::dumpAsString($model->contents), 'Cms.Workflow');
        
//        $criteria = new CDbCriteria();
//        $criteria->with = array(
//            'contents'=>array(
//                'together'=>true
//            )
//        );
//        $criteria->compare('name', $workflow->site_id);
//        if (count($masterLayouts) && $workflow->master_layout_revision && array_key_exists($workflow->master_layout_revision, $masterLayouts))
//        {
//            $criteria->compare('contents.id', $workflow->master_layout_revision);
//        }
//        $template = Template::model()->find($criteria);
//        if (is_object($template))
//        {
//            if (is_array($template->contents) && count($template->contents))
//            {
//                $templateContent = $template->contents[0];
//            }
//            else
//            {
//                $templateContent = new TemplateContent();
//                $templateContent->template_id = $template->id;
//            }
//        }
//        else
//        {
//            $template = new Template();
//            $templateContent = new TemplateContent();
//        }
        
//        $newRevision = false;
        //Yii::trace('$template '.CVarDumper::dumpAsString($template), 'Cms.Workflow');
        
//        if (isset($_POST['Workflow'], $_POST['Template'], $_POST['TemplateContent']))
        if (isset($_POST['Workflow']))
        {
//            $newRevision = isset($_POST['new_revision']) && $_POST['new_revision'] ? true : false;
            $workflow->attributes = $_POST['Workflow'];
//            $template->attributes = $_POST['Template'];
//            $template->name = $workflow->site_id;
//            $template->group = 'master';
//            $templateContent->attributes = $_POST['TemplateContent'];
//            $templateContentAttributes = $templateContent->attributes;
//            if (! $newRevision)
//            {
//                if (isset($templateContentAttributes['log']))
//                {
//                    unset($templateContentAttributes['log']);
//                }
//            }
//            $templateContentAttributes = array_keys($templateContentAttributes);
            
//            $valid = $workflow->validate() && $template->validate() && $templateContent->validate($templateContentAttributes);
            $valid = $workflow->validate(); // && $template->validate() && $templateContent->validate($templateContentAttributes);
            if ($valid)
            {
//                $template->status = true;
//                if (! $template->save(false))
//                {
//                    Yii::log(CVarDumper::dumpAsString($template->getErrors()), CLogger::LEVEL_ERROR, 'Cms.Workflow');
//                }
//                else
//                {
                    //generate new revision
//                    if ($newRevision)
//                    {
//                        $templateContent->setIsNewRecord(true);
//                        $templateContent->id = null;
//                    }
//                    else
//                    {
                        //change revision and change content
                        //if ($workflow->master_layout_revision != $templateContent->id)
//                        {
//                            $templateContent = TemplateContent::model()->findByPk($workflow->master_layout_revision);
//                            if (!is_object($templateContent))
//                            {
//                                $templateContent = new TemplateContent();
//                            }
//                            $templateContent->attributes = $_POST['TemplateContent'];
//                            $templateContent->validate($templateContentAttributes);
//                        }
//                    }
                    //$templateContent->template_id = $template->id;
//                    if ($templateContent->getIsNewRecord())
//                    {
//                        $command = Yii::app()->db->createCommand();
//                        $maxRevision = $command->select('MAX(revision_id)')
//                            ->from(SITE_TABLE_PREFIX.'template_content')
//                            ->where('template_id = :template_id', array(':template_id'=>$templateContent->template_id))
//                            ->queryScalar();
//                        $templateContent->revision_id = $maxRevision+1;
//                    }
//                    $templateContent->status = true;
//                    if (! $templateContent->save(false))
//                    {
//                        Yii::log(CVarDumper::dumpAsString($templateContent->getErrors()), CLogger::LEVEL_ERROR, 'Cms.Workflow');
//                        $template->delete();
//                    }
//                    else
//                    {
//                        if ($newRevision)
//                        {
//                            $workflow->master_layout_revision = $templateContent->id;
//                        }
                        $createWorkflow = $workflow->getIsNewRecord();
                        if (! $workflow->save(false))
                        {
                            Yii::log(CVarDumper::dumpAsString($workflow->getErrors()), CLogger::LEVEL_ERROR, 'Cms.Workflow');
//                            $template->delete();
//                            $templateContent->delete();
                        }
                        else
                        {
                            if ($createWorkflow)
                            {
                                //active pages same workflow
                                $sameWorkflowId = $this->post('same_workflow', 0);
                                if ($sameWorkflowId)
                                {
                                    FSM::_run('Cms.workflow.activePageSameWorkflow', array('source_workflow_id'=>$workflow->id, 'target_workflow_id'=>$sameWorkflowId));
                                }
                                //active pages for initital or final
                                if ($workflow->type == Workflow::TYPE_INITITAL || $workflow->type == Workflow::TYPE_FINAL)
                                {
                                    FSM::_run('Cms.page.initCurrentByWorkflow', array('workflow_id'=>$workflow->id,'site_id'=>$workflow->site_id));
                                }
                            }
                            $this->message = Yii::t('Core','Item has been saved successfully.');
                            $this->redirect(array('update', 'id'=>$workflow->id));
                        }
//                    }
//                }
            }
            else
            {
                Yii::log(CVarDumper::dumpAsString($workflow->getErrors()), CLogger::LEVEL_ERROR, 'Cms.Workflow');
                Yii::log(CVarDumper::dumpAsString($template->getErrors()), CLogger::LEVEL_ERROR, 'Cms.Workflow');
                Yii::log(CVarDumper::dumpAsString($templateContent->getErrors()), CLogger::LEVEL_ERROR, 'Cms.Workflow');
            }
        }
        
        $sites = FSM::run('Cms.site.getList')->models;
        if (count($sites))
            $sites = CHtml::listData($sites, 'id', 'name');
        //create new, active pages same workflow.
        $workflows = array();
        if (! $id)
        {
            $workflows = FSM::run('Cms.Workflow.getListBySite', array('site_id'=>$workflow->site_id))->models;
            if (count($workflows))
                $workflows = CHtml::listData($workflows, 'id', 'name');
        }
        
//        if (! count($templateContent->css_files))
//        {
//            $templateContent->css_files = array('');
//        }
//        
//        if (! count($templateContent->js_files))
//        {
//            $templateContent->js_files = array('');
//        }
//        $templateContent->log = '';
        
        $this->render('update', array(
            'workflow' => $workflow,
//            'template' => $template,
//            'templateContent' => $templateContent,
//            'newRevision' => $newRevision,
//            'masterLayouts' => $masterLayouts,
            'workflows' => $workflows,
            'sites'=>$sites,
        ));
    }
    
    public function actionPage()
    {
        $this->pageId = $this->get('page_id', 0);
        $revision = $this->get('revision_id', 0);
        $workflowId = $this->get('workflow_id', null);
        
        $model=new Workflow('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Workflow'])){
            $model->attributes=$_GET['Workflow'];
        }
        
        $criteria=new CDbCriteria;
        //use site_id column store page revision active
        if ($model->site_id)
        {
            $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'page_current_revision pcr ON pcr.workflow_id = t.id';
            $criteria->compare('pcr.revision', $model->site_id);
            $criteria->compare('pcr.page_id', $this->pageId);
        }
        $criteria->compare('t.site_id', Yii::app()->cmsManager->site['id']);
        $criteria->compare('locale_id',$model->locale_id);
        $criteria->compare('name',$model->name);
        $criteria->compare('url',$model->url, true);
        $criteria->compare('id',$workflowId);
        if (!Yii::app()->authManager->isAssigned(FAuthManager::ROLE_ADMINISTRATORS, Yii::app()->user->id))
        {
            if (Yii::app()->authManager->isAssigned('Editor', Yii::app()->user->id))
            {
                Yii::import('User.models.WorkflowOwner');
                $myWorkflows = WorkflowOwner::model()->findAllByAttributes(array('user_id'=>Yii::app()->user->id));
                if (is_array($myWorkflows) && count($myWorkflows))
                {
                    $myWorkflows = CHtml::listData($myWorkflows, 'workflow_id', 'workflow_id');
                    $criteria->addInCondition('id', $myWorkflows);
                }
                else
                    $criteria->addCondition('1=0');
            }
            else
            {
                //not allow see any workflows
                $criteria->addCondition('1=0');
            }
        }
        $dataProvider = new CActiveDataProvider('Workflow', array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'t.name',
            ),
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        ));
        
        //find all page revisions
        $criteria = new CDbCriteria;
        $criteria->compare('page_id',$this->pageId);
        $criteria->order = 'id DESC';
        $revisions = PageRevision::model()->findAll($criteria);
        if (is_array($revisions) && count($revisions))
            $revisions = CHtml::listData($revisions, 'id', 'id');
        else
            $revisions = array();
        $this->revisions = $revisions;
        
        if (Yii::app()->request->getIsAjaxRequest())
        {
            $html = $this->renderPartial('page', array(
                'model' => $model,
                'dataProvider' => $dataProvider,
            ), true, true);
            $html = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)\.css" \/>/', '', $html);
            $html = preg_replace('/<script type="text\/javascript" src="([^"]+)\.js"><\/script>/', '', $html);
            echo $html;
        }
        else
        {
            $this->render('page', array(
                'model' => $model,
                'dataProvider' => $dataProvider,
            ));
        }
    }
    
    public $revisions;
    public $pageId;
    public $selected=array();
    
    public function revisionDDList($workflowId){
        $selected = $this->getSelectedRevision($workflowId);
        return CHtml::dropDownList('revision_'.$workflowId, $selected, $this->revisions, array('prompt'=>'---Select Revision---'));
    }
    
    protected function getSelectedRevision($workflowId)
    {
        $key = $this->pageId.'_'.$workflowId;
        if (!isset($this->selected[$key]))
        {
            $command = Yii::app()->db->createCommand();
            $this->selected[$key] = $command->select('revision')
                ->from(SITE_TABLE_PREFIX.'page_current_revision')
                ->where('page_id=:page_id AND workflow_id=:workflow_id', array(
                    ':page_id'=>$this->pageId,
                    ':workflow_id'=>$workflowId,
                ))
                ->queryScalar();
        }
        return $this->selected[$key];
    }
    
    public function getPageUrl($workflow)
    {
        $selected = $this->getSelectedRevision($workflow->id);
        if ($selected)
        {
            $page = Page::model()->findByPk($this->pageId);
            if (is_object($page) && is_object($page->defaultUrl))
                return "http://".trim($workflow->url, "/")."/".trim($page->defaultUrl->url, "/");
        }
        return "http://".trim($workflow->url, "/")."/";
    }
}
